package service;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;

import model.Card;
import model.Pricedata;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;

import de.laures.cewolf.DatasetProduceException;
import de.laures.cewolf.DatasetProducer;
import de.laures.cewolf.links.CategoryItemLinkGenerator;
import de.laures.cewolf.tooltips.CategoryToolTipGenerator;

public class PricedataData implements DatasetProducer,
		CategoryToolTipGenerator, CategoryItemLinkGenerator, Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Log log = LogFactory.getLog(PricedataData.class);
	private String[] categories  = null;
	private Card card = null;
	private final String[] seriesNames = { "selling","buying"};
	
	public PricedataData() {
		// TODO Auto-generated constructor stub
	}

	public PricedataData(Card card) {
		this.card = card;
		List<Pricedata> pds = card.getOrderedPricedataByDateAscending();
		categories = new String[pds.size()];
		int i = 0;
		for(Pricedata pd : pds){
			categories[i] = new Date(pd.getDate()).toLocaleString();
			i++;
		}
		
	}
	@Override
	public String getProducerId() {
		// TODO Auto-generated method stub
		return "PridedataData Dataset producer"+card;
		
	}

	@Override
	public boolean hasExpired(Map arg0, Date since) {
		return true;

	}

	@Override
	public Object produceDataset(Map params) throws DatasetProduceException {
		log.debug("producing Data");
		DefaultCategoryDataset dataset = new DefaultCategoryDataset(){
			/**
			 * @see java.lang.Object#finalize()
			 */
			protected void finalize() throws Throwable {
				super.finalize();
				log.debug(this +" finalized.");
			}
        };
        List<Pricedata> pds = card.getOrderedPricedataByDateAscending();
		for(int i = 0; i < pds.size();i++){
        	dataset.addValue(pds.get(i).getSellPrice()/100d, seriesNames[0], categories[i]);
        	dataset.addValue(pds.get(i).getBuyPrice()/100d, seriesNames[1], categories[i]);
        	
        }
        

		return dataset;
	}

	@Override
	public String generateToolTip(CategoryDataset arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub
		return categories[arg2]+" - Price: "+arg0.getValue(arg1, arg2);
	}

	@Override
	public String generateLink(Object arg0, int series, Object arg2) {
		return seriesNames[series];

	}
	public void setCard(Card c){
		this.card = c;
		List<Pricedata> pds = card.getOrderedPricedataByDateAscending();
		categories = new String[pds.size()];
		int i = 0;
		for(Pricedata pd : pds){
			categories[i] = new Date(pd.getDate()).toLocaleString();
			i++;
		}
	}

}
